package com.byit.shrio.session;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author wangx
 */
public class SessionListener implements HttpSessionListener {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 统计在线人数
     * juc包下线程安全自增
     */
    private final AtomicInteger sessionCount = new AtomicInteger(0);

    private static Map<String, HttpSession> sessions = new HashMap<>();

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        int i = sessionCount.incrementAndGet();
        se.getSession().getServletContext().setAttribute("count", i);
        sessions.put(se.getSession().getId(), se.getSession());
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        int i = sessionCount.decrementAndGet();
        se.getSession().getServletContext().setAttribute("count", i);
        sessions.remove(se.getSession().getId());
    }

    /**
     * 获取在线人数使用
     *
     * @return
     */
    public AtomicInteger getSessionCount() {
        return sessionCount;
    }

    public List<HttpSession> getActiveSessions() {
        return new ArrayList<>(sessions.values());
    }
}